<?php
namespace App\Http\Controllers\Api;




use App\Http\Controllers\Controller;

class Wxpaybatches extends Controller
{
  protected $exceptAuthAction = [];


    /**
     * @api {POST} api/Wxpaybatches/wxBatches  商家转账到零钱(nh)
     * @apiName 商家转账到零钱
     * @apiGroup Wxpaybatches
     *
     * @apiHeader {String} partner_trade_no 提现订单号(必)
     * @apiHeader {String} amount 金额(必)
     * @apiHeader {String} openid 用户唯一标识(必)
     *
     * @apiSuccess {Object} code 响应码, 如： 200
     * @apiSuccess {Object} msg 响应信息, 如： 操作成功/success
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "code": 200,
     *       "message": "success",
     *       "data": {
     *           "code": "INVALID_REQUEST",
     *           "message": "产品权限异常"
     *       }
     *   }
     */

public function wxBatches($openid,$money,$out_batch_no){

        // 微信请求地址
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        // $out_detail_no = date('YmdHis').rand(0,9999).time();
        $transfer_detail_list = array(
            [
                'out_detail_no'   => $out_batch_no, // 商户系统内部的订单号
                'transfer_amount' => intval($money * 100),// 单笔转账金额，单位为分。
                'transfer_remark' => '账户提现', // 转账备注。
                'openid'          => $openid,    // 收款用户的 OpenID。
            ],
        );
        $params = [
            'appid'                => config('pay.wechat.default.app_id'),
            'out_batch_no'         => $out_batch_no,
            'batch_name'           => '账户提现',
            'batch_remark'         => '账户提现',
            'total_amount'         => intval($money * 100),
            'total_num'            => 1,
            'transfer_detail_list' => $transfer_detail_list,
            'notify_url' => 'https://new.dev.czmb.tech/api/pay/web_shop_pay',
        ];
        info($params);
        $token = $this->getToken($params);
        $res = $this->https_request($url, json_encode($params), $token);
        return json_decode($res, true);
    }


    /**
     * 构造请求
     */
    public function https_request($url, $data = null, $token){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 添加请求头
        $headers =     [
            'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 获取token
     */
    public function getToken($pars){
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $http_method = 'POST';
        $timestamp   = time();
        $url_parts   = parse_url($url);
        $nonce       = $timestamp . rand('10000','99999');
        $body        = json_encode((object)$pars);              // 请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"          => false,
                "verify_peer_name"     => false,
            ]
        ];
        $apiclient_cert_path = config('pay.wechat.default.mch_public_cert_path');//'./../cert/apiclient_cert.pem';
        info('获取到的证书文件'.$apiclient_cert_path);
        $apiclient_key_path  = config('pay.wechat.default.mch_secret_cert');//'./../cert/apiclient_key.pem';
        if(!file_exists($apiclient_cert_path)){
            info($apiclient_cert_path.'路径下面的文件不存在');
        }else{
            $certContent = file_get_contents($apiclient_cert_path);
            info('获取到的证书内容'.$certContent);
        }
        $apiclient_cert_arr = openssl_x509_parse(@file_get_contents($apiclient_cert_path, false, stream_context_create($stream_opts)));
        info('拿到的证书',$apiclient_cert_arr);
        // 证书序列号
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];
        // 密钥
        $mch_private_key    = @file_get_contents($apiclient_key_path, false, stream_context_create($stream_opts));
        // 商户id：文档顶部定义
        $merchant_id        = config('pay.wechat.default.mch_id');
        $canonical_url      = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message            = $http_method . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        // 签名
        $sign   = base64_encode($raw_sign);
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token  = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $merchant_id, $nonce, $timestamp, $serial_no, $sign);
        // 微信返回token
        return $token;
    }



    /**
     * @api {POST} api/Wxpaybatches/queryBatches  单号查询批次(nh)
     * @apiName 单号查询批次
     * @apiGroup Wxpaybatches
     *
     * @apiHeader {String} partner_trade_no 提现订单号(必)
     * @apiHeader {String} out_batch_no 商家订单号(必)
     *
     *
     * @apiSuccess {Object} code 响应码, 如： 200
     * @apiSuccess {Object} msg 响应信息, 如： 操作成功/success
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "code": 200,
     *       "message": "success",
     *       "data": {
     *           "code": "INVALID_REQUEST",
     *           "message": "产品权限异常"
     *       }
     *   }
     */
    public function queryBatches(){
        $param = 'plfk2020042013';
       $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$param;
       $pars = [
            'appid'                => config('pay.wechat.default.app_id'),
            'out_batch_no'         => $param,
            'need_query_detail'           => true,
        ];
       $token  = $this->getToken($pars);
       $res = $this->curlGet($url,json_encode($pars),$token);//发送请求
       return Response::success($res);
    }


   public function curlGet($url , $data = null,$token){
        $ch= curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        if (!empty($data)) {
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
         }
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
       $headers = [
            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
           curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }






}
